import React, { useState } from "react";
import {
  getProcessingList,
  taskRetry,
} from "@/services/api/api-intelligent-processing";
import { useIntl } from "@umijs/max";
import {
  Tag,
  Progress,
  message,
  Card,
  Button,
  Tooltip,
  Space,
  Dropdown,
  Modal,
} from "antd";
import { ProList } from "@ant-design/pro-components";
import {
  RedoOutlined,
  MoreOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  FileTextOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";

interface Task {
  task_id: string;
  folder_path: string;
  status: "running" | "success" | "failed";
  progress: number;
  created_at: string;
  errorMessage?: string;
}

const TaskProcessing: React.FC = () => {
  const { formatMessage } = useIntl();
  const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>(
    {}
  );
  const [allRetryLoading, setAllRetryLoading] = useState(false);

  // 渲染状态标签
  const renderStatusTag = (status: string) => {
    switch (status) {
      case "running":
        return (
          <Tag icon={<SyncOutlined spin />} color="processing">
            进行中
          </Tag>
        );
      case "failed":
        return (
          <Tag icon={<CloseCircleOutlined />} color="error">
            失败
          </Tag>
        );
      case "success":
        return (
          <Tag icon={<CheckCircleOutlined />} color="success">
            成功
          </Tag>
        );
      default:
        return <Tag>未知</Tag>;
    }
  };

  const handleTaskRetry = async (taskId: string) => {
    // 设置单个任务的加载状态
    setLoadingStates((prev) => ({ ...prev, [taskId]: true }));

    try {
      const res = await taskRetry({ task_ids: [taskId] });
      if (res.code === 0) {
        message.success("任务已重新处理");
      } else {
        message.error("重试失败，请稍后再试");
      }
    } catch (error) {
      message.error("重试失败，请稍后再试");
    } finally {
      // 清除单个任务的加载状态
      setLoadingStates((prev) => ({ ...prev, [taskId]: false }));
    }
  };

  const handleAllRetry = async () => {
    Modal.confirm({
      title: "确认全部重试",
      icon: <ExclamationCircleOutlined />,
      content: "确定要重新处理所有失败的任务吗？",
      onOk: async () => {
        setAllRetryLoading(true);
        try {
          // 获取所有失败的任务ID
          const response = await getProcessingList({
            currentPage: 1,
            pageSize: 1000, // 获取足够多的数据
          });

          if (response.code === 0) {
            const failedTasks = response.data.data.filter(
              (task: Task) => task.status === "failed"
            );
            const failedTaskIds = failedTasks.map((task: Task) => task.task_id);

            if (failedTaskIds.length === 0) {
              message.info("没有失败的任务需要重试");
              return;
            }

            const res = await taskRetry({ task_ids: failedTaskIds });
            if (res.code === 0) {
              message.success(
                `已开始重新处理 ${failedTaskIds.length} 个失败任务`
              );
            } else {
              message.error("批量重试失败，请稍后再试");
            }
          }
        } catch (error) {
          message.error("批量重试失败，请稍后再试");
        } finally {
          setAllRetryLoading(false);
        }
      },
    });
  };

  // 渲染操作菜单
  const renderActions = (item: Task) => {
    if (item.status === "failed") {
      return [
        <Tooltip title="重新处理此任务" key="retry">
          <Button
            type="link"
            icon={<RedoOutlined />}
            onClick={() => handleTaskRetry(item.task_id)}
            loading={loadingStates[item.task_id] || false}
          >
            重试
          </Button>
        </Tooltip>,
      ];
    }

    return null;
  };

  return (
    <Card
      title="任务处理列表"
      style={{ margin: 24 }}
      extra={
        <Button
          type="primary"
          onClick={handleAllRetry}
          loading={allRetryLoading}
          icon={<RedoOutlined />}
        >
          全部重试
        </Button>
      }
    >
      <ProList<Task>
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条任务`,
        }}
        request={async (params = {}) => {
          try {
            const { current = 1, pageSize = 10 } = params;
            const response = await getProcessingList({
              currentPage: current,
              pageSize: pageSize,
            });

            if (response.code === 0) {
              return {
                data: response.data.data,
                total: response.data.total,
                success: true,
              };
            } else {
              message.error("加载任务列表失败");
              return {
                data: [],
                total: 0,
                success: false,
              };
            }
          } catch (error) {
            message.error("加载任务列表失败");
            return {
              data: [],
              total: 0,
              success: false,
            };
          }
        }}
        rowKey="task_id"
        headerTitle={false}
        search={false}
        options={false}
        metas={{
          title: {
            dataIndex: "name",
            render: (_, record) => (
              <div style={{ display: "flex", alignItems: "center" }}>
                <div>
                  <div style={{ fontWeight: 500 }}>{record.folder_path}</div>
                </div>
              </div>
            ),
          },
          description: {
            dataIndex: "createdAt",
            render: (_, record) => (
              <div>
                <Space direction="vertical" size="small">
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <ClockCircleOutlined
                      style={{ marginRight: 4, fontSize: 12 }}
                    />
                    <span style={{ fontSize: 12 }}>
                      创建时间:{" "}
                      {dayjs(record.created_at).format("YYYY-MM-DD HH:mm:ss")}
                    </span>
                  </div>



                  {record.status === "failed" && record.errorMessage && (
                    <Tooltip title={record.errorMessage}>
                      <span
                        style={{
                          fontSize: 12,
                          color: "#ff4d4f",
                          display: "block",
                          maxWidth: 300,
                          whiteSpace: "nowrap",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                        }}
                      >
                        错误: {record.errorMessage}
                      </span>
                    </Tooltip>
                  )}
                </Space>
              </div>
            ),
          },
          subTitle: {
            render: (_, record) => {
              return <div>{renderStatusTag(record.status)}</div>;
            },
          },
          actions: {
            render: (_, record) => renderActions(record),
          },
        }}
        locale={{
          emptyText: "暂无任务数据",
        }}
      />
    </Card>
  );
};

export default TaskProcessing;
